{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install langchain-core langchain-openai langchain-exa"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"...\"\n",
    "os.environ[\"EXA_API_KEY\"] = \"...\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
    "os.environ[\"LANGCHAIN_API_KEY\"] = \"...\"\n",
    "os.environ[\"LANGCHAIN_PROJECT\"] = \"erick-default\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_exa import ExaSearchRetriever\n",
    "\n",
    "retriever = ExaSearchRetriever(k=3, highlights=True)\n",
    "documents = retriever.invoke(\"best time to visit japan\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['It\\x92s a cluster of public holidays: Shōwa Day (29 April), Constitution Day (3 May), Greenery Day (4 May) and Children\\x92s Day (5 May) that sees many Japanese people leaving the cities to visit their families. Trains are full, hotel prices rocket, and a lot of restaurants and shops close in the cities. Joining in with the festivities can be a nice experience, but generally speaking Golden Week is not the best time to travel in Japan. Late autumn to March and high summer (July and August) tend to be the cheapest times to visit Japan.']\n"
     ]
    }
   ],
   "source": [
    "\n",
    "print(documents[0].metadata[\"highlights\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "https://www.responsibletravel.com/holidays/japan/travel-guide/best-time-to-visit-japan\n"
     ]
    }
   ],
   "source": [
    "\n",
    "print(documents[0].metadata[\"url\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "<source>\n",
      "    <url>https://www.responsibletravel.com/holidays/japan/travel-guide/best-time-to-visit-japan</url>\n",
      "    <highlights>['It\\x92s a cluster of public holidays: Shōwa Day (29 April), Constitution Day (3 May), Greenery Day (4 May) and Children\\x92s Day (5 May) that sees many Japanese people leaving the cities to visit their families. Trains are full, hotel prices rocket, and a lot of restaurants and shops close in the cities. Joining in with the festivities can be a nice experience, but generally speaking Golden Week is not the best time to travel in Japan. Late autumn to March and high summer (July and August) tend to be the cheapest times to visit Japan.']</highlights>\n",
      "</source>\n",
      "\n",
      "\n",
      "<source>\n",
      "    <url>https://alljapantours.com/japan/travel/when-to-go/The-Best-Time-to-Visit-Japan/</url>\n",
      "    <highlights>['Without a doubt, it’s the most romantic time of year and attracts millions of visitors from all over the world. And that’s not an exaggeration. The iconic cherry blossom season in Japan typically lasts from late-March to early April in most parts of the country, although there are some exceptions. For some travelers, seeing cities like Tokyo and Kyoto smattered in shades of pink is reason enough to cross oceans.']</highlights>\n",
      "</source>\n",
      "\n",
      "\n",
      "<source>\n",
      "    <url>https://www.lonelyplanet.com/articles/best-time-to-travel-to-japan</url>\n",
      "    <highlights>[\"Japan's rainy season typically straddles these two months on Honshu, Japan’s main island, meaning hotel prices will be a little cheaper and outdoor excursions a little less thronged.\\xa0 December to March is the best time for snow and low prices In winter, sights are uncrowded, and accommodation is at its cheapest, except in Japan's ski resorts as the ski season hits its stride. Snow bunnies insist that Japan has some of the finest powder on the planet, particularly on the slopes of Hokkaidō in the far north.\"]</highlights>\n",
      "</source>\n",
      "\n"
     ]
    }
   ],
   "source": [
    "from langchain_exa import ExaSearchRetriever\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain_core.runnables import RunnableLambda\n",
    "\n",
    "\n",
    "retriever = ExaSearchRetriever(k=3, highlights=True)\n",
    "\n",
    "document_prompt = PromptTemplate.from_template(\"\"\"\n",
    "<source>\n",
    "    <url>{url}</url>\n",
    "    <highlights>{highlights}</highlights>\n",
    "</source>\n",
    "\"\"\")\n",
    "\n",
    "document_chain = RunnableLambda(\n",
    "    lambda document: {\n",
    "        \"highlights\": document.metadata[\"highlights\"], \n",
    "        \"url\": document.metadata[\"url\"]\n",
    "    }\n",
    ") | document_prompt\n",
    "\n",
    "retrieval_chain = retriever | document_chain.map() | (lambda docs: \"\\n\".join([i.text for i in docs]))\n",
    "\n",
    "print(retrieval_chain.invoke(\"best time to visit japan\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.runnables import RunnablePassthrough, RunnableParallel\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "generation_prompt = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"You are an expert research assistant. You use xml-formatted context to research people's questions.\"),\n",
    "    (\"human\", \"\"\"\n",
    "Please answer the following query based on the provided context. Please cite your sources at the end of your response.:\n",
    "     \n",
    "Query: {query}\n",
    "---\n",
    "<context>\n",
    "{context}\n",
    "</context>\n",
    "\"\"\")\n",
    "])\n",
    "\n",
    "llm = ChatOpenAI()\n",
    "\n",
    "chain = RunnableParallel({\n",
    "    \"query\": RunnablePassthrough(),\n",
    "    \"context\": retrieval_chain,\n",
    "}) | generation_prompt | llm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='The best time to visit Japan depends on several factors, including weather, festivals, and personal preferences. However, there are a few key periods that are considered popular times to visit.\\n\\nOne of the most popular times to visit Japan is during the cherry blossom season, which typically occurs from late March to early April. This is a romantic and beautiful time of year when cities like Tokyo and Kyoto are adorned with pink cherry blossoms. Millions of visitors from around the world come to Japan to witness this natural spectacle.\\n\\nAnother popular time to visit Japan is in late autumn to March. During this time, the weather is generally cool and the tourist crowds are smaller. This period is considered off-peak, which means that prices for accommodation and attractions tend to be lower. It is a great time to explore Japan\\'s cultural attractions without the crowds.\\n\\nHigh summer, specifically July and August, is another time that tends to be cheaper to visit Japan. However, it is worth noting that these months can be quite hot and humid, especially in the cities. If you can tolerate the heat, this can be a budget-friendly time to visit.\\n\\nAdditionally, the rainy season in Japan typically falls between June and July. While this may not be the most ideal time for outdoor activities, it can be a good time to find cheaper hotel prices and fewer crowds.\\n\\nFor those interested in winter activities, December to March is the best time to visit Japan for snow and low prices. Sights are uncrowded, and accommodation is at its cheapest during this time, except in Japan\\'s ski resorts where the ski season is in full swing. Japan is known for having some of the finest powder on the planet, particularly in Hokkaidō in the far north.\\n\\nIn conclusion, the best time to visit Japan depends on personal preferences, but the cherry blossom season, late autumn to March, high summer, and winter are popular times to consider.\\n\\nSources:\\n- \"Best time to visit Japan\" - Responsible Travel (https://www.responsibletravel.com/holidays/japan/travel-guide/best-time-to-visit-japan)\\n- \"The Best Time to Visit Japan\" - All Japan Tours (https://alljapantours.com/japan/travel/when-to-go/The-Best-Time-to-Visit-Japan/)\\n- \"Best time to travel to Japan\" - Lonely Planet (https://www.lonelyplanet.com/articles/best-time-to-travel-to-japan)')"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain.invoke(\"best time to visit japan\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
